#define _CRT_SECURE_NO_WARNINGS

class Solution {
public:
    vector<vector<int>> matrixBlockSum(vector<vector<int>>& mat, int k) {
        vector<vector<int>> ret(mat.size(), vector<int>(mat[0].size()));
        vector<vector<int>> dp(mat.size() + 1, vector<int>(mat[0].size() + 1));

        for (int i = 1; i < dp.size(); i++)
        {
            for (int j = 1; j < dp[0].size(); j++)
                dp[i][j] = mat[i - 1][j - 1] + dp[i - 1][j] + dp[i][j - 1] - dp[i - 1][j - 1];
        }

        for (int i = 0; i < ret.size(); i++)
        {
            for (int j = 0; j < ret[0].size(); j++)
            {
                int x1 = max(0, i - k), y1 = max(0, j - k);
                int x2 = min((int)ret.size() - 1, i + k), y2 = min((int)ret[0].size() - 1, j + k);

                ret[i][j] = dp[x2 + 1][y2 + 1] - dp[x1 - 1 + 1][y2 + 1] - dp[x2 + 1][y1 - 1 + 1] + dp[x1 - 1 + 1][y1 - 1 + 1];
            }
        }

        return ret;
    }
};